package com.ys.controller.api.storage;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.amazonorder.TpAmazonShopOrderDaily;
import com.ys.entity.storage.TccAllocate;
import com.ys.entity.storage.TccAllocateDetail;
import com.ys.entity.sys.YsCol;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.storage.TccAllocateDetailEnum;
import com.ys.enume.storage.TccAllocateEnum;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.business.TpBoutiqueCartService;
import com.ys.service.storage.TccAllocateService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/*
 * 预约调拨单
 */
@Controller
@RequestMapping("/api/inter/tccAllocate")
public class ApiInterTccAllocateController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private TccAllocateService tccAllocateService;
	@Autowired
	private TpBoutiqueCartService tpBoutiqueCartService;
	
	@Autowired
	private CommonApiService<TccAllocateDetail> commonApiServiceDetail;
	
	@Autowired
	private CommonApiService<TccAllocate> commonApiTccAllocateService;

	private final String PERMISSIONS_ADD = "tccAllocate:add";
	private final String PERMISSIONS_VIEW = "tccAllocate:view";
	private final String PERMISSIONS_EXPORT = "tccAllocate:export";
    /**
     * 设置查询的cond的sql设置
     */
    private TccAllocateDetail setSeachSql(TccAllocateDetail cond){
        cond.setStatus(1);//数据过滤
		
		cond
			.addField("(A.Num * A.SinglePrice) totalPrice,A.allocateCancelNum,(A.singlePrice * A.distributeNum) distributedTotalPrice");

		cond.addLeftJoin("TCC_Allocate B ON B.Bid = A.BidAllocate")
			.addField("B.Bid bid")
			.addField("B.EffectStock effectStock")
			.addField("B.Type type");
			
		cond.addLeftJoin("TS_UserChange C on C.Id = B.CreateChangeId")
			.addField("C.UserId createUserId");
		
		cond.addLeftJoin("YS_ProcInst D on D.Bid = A.BidAllocate")
			.addField("D.UpdateTime auditTime");

		cond.addLeftJoin("THR_OperateCompanyApply E ON  E.VGsBm = A.VgsbmTo")
				.addField("E.CUser cUser");
		
		cond.setOrderby("A.Id desc");
		//权限
		cond = commonApiServiceDetail.dataAuth(MenuId.TCC_Allocate, cond);
        return  cond;
    }

	@RequiresPermissions(PERMISSIONS_VIEW)
	@RequestMapping("/searchDetail")
    @ResponseBody
	public LayuiTableVoJA searchDetail(@ModelAttribute TccAllocateDetail cond){
		
        cond = setSeachSql(cond);
		
		LayuiTableVoJA vo = commonApiServiceDetail.searchLay(cond);
		return vo;
	}

	//预约调拨单详情 - 未分配 弹框
	@RequiresPermissions(PERMISSIONS_VIEW)
	@RequestMapping("/searchDetailUnDistribute")
    @ResponseBody
	public LayuiTableVoJA searchDetailUnDistribute(@ModelAttribute TccAllocateDetail cond){
		
		cond.setStateDistribute(TccAllocateDetailEnum.StateDistribute.NO.value);
		
		cond
			.addField("A.Num allocateNum") // 调拨数量
			//.addField("A.SinglePrice allocateSinglePrice") // 调拨单价
			//.addField("(A.Num * A.SinglePrice) allocateTotalPrice") // 调拨总价
			//.addField("(select ISNULL(sum(Num),0) from TCC_DistributeDetail where AllocateDetailId = A.Id) distributedNum") // 已分配数量
			//.addField("(select ISNULL(sum(Num * SinglePrice),0) from TCC_DistributeDetail where AllocateDetailId = A.Id) distributedTotalPrice") // 已分配总额
			//.addField("A.Num - (select ISNULL(sum(Num),0) from TCC_DistributeDetail where AllocateDetailId = A.Id) unDistributeNum") // 未分配数量
			//.addField("(select ISNULL(sum(Num),0) from TCC_AllocateCancelDetail where AllocateDetailId = A.Id) canceledNum") // 已取消数量
			//.addField("(select ISNULL(sum(Num * Bprice),0) from TP_ProductBasisComponent where Pcode = A.ProductCode) purchaseSinglePrice"); // 采购单价
		
			.addLeftJoin("TCC_Allocate B ON B.Bid = A.BidAllocate")
			.addField("B.Bid bid")
			.addField("B.EffectStock effectStock")
			.addField("B.Type typeAllocate")
			.addField("A.DistributeNum distributedNum") // 已分配数量
			.addField("A.AllocateCancelNum canceledNum") // 已取消数量
			.where("B.EffectStock = " + FlowEnum.EffectStock.EFFECTED.value) //流程已生效
//			.where("B.Type = "+ TccAllocateEnum.Type.PU_PIN.value) //普通调拨；精品调拨不能取消

		;

		
		cond.setOrderby("A.Id desc");
		
		LayuiTableVoJA vo = commonApiServiceDetail.searchLay(cond);
		return vo;
	}

    //预约调拨单详情 - 手工分配 弹框
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/searchDetailUnDistributeFp")
    @ResponseBody
    public LayuiTableVoJA searchDetailUnDistributeFp(@ModelAttribute TccAllocateDetail cond,String vgsbmFrom){

        cond.setStateDistribute(TccAllocateDetailEnum.StateDistribute.NO.value);

        cond
                .addField("A.Num allocateNum") // 调拨数量
    			.addField("A.SinglePrice allocateSinglePrice") // 调拨单价
                .addField("(A.Num * A.SinglePrice) allocateTotalPrice") // 调拨总价
                .addField("A.DistributeNum distributedNum") // 已分配数量
                .addField("A.DistributeNum * A.SinglePrice distributedTotalPrice") // 已分配总额
                .addField("A.MayDistributeNum unDistributeNum") // 未分配数量
                .addField("A.AllocateCancelNum canceledNum") // 已取消数量
                .addField("A.SinglePrice purchaseSinglePrice") // 采购单价
    			.addLeftJoin("TCC_Allocate B ON B.Bid = A.BidAllocate")
                .addField("B.Bid bid")
                .addField("B.EffectStock effectStock")
                .addField("B.Type typeAllocate")
			    .where("B.EffectStock = " + FlowEnum.EffectStock.EFFECTED.value + "AND A.vgsbmFrom = '" + vgsbmFrom + "'" + " AND A.StateDistribute = 0");

           cond.setOrderby("A.Id desc");

        LayuiTableVoJA vo = commonApiServiceDetail.searchLay(cond);
        return vo;
    }
	
	/**
	 * 验证账户余额是否够调拨
	 */
	@PostMapping("/checkAccount")
    @ResponseBody
	public R checkAccount(HttpServletRequest request,
			String subData) {
		
		return tccAllocateService.checkAccount(subData);
	}
	
	/**
	 * 新增
	 * @throws Exception 
	 */
	@RequiresPermissions(PERMISSIONS_ADD)
	@PostMapping("/add")
    @ResponseBody
	public R add(HttpServletRequest request,
			String bid, Integer type, String subData) throws Exception{
		
		if (type == TccAllocateEnum.Type.JING_PIN.value) {
			bid = commonApiTccAllocateService.getCommonNextBid(MenuId.TCC_Allocate);
		}
		
		R r = tccAllocateService.add(bid, type, subData, MenuId.TCC_Allocate);
		{
			if (type == TccAllocateEnum.Type.JING_PIN.value) {
				if (r.getCode() == R.Code.SUCCESS.value) {
					TccAllocate tccAllocate = new TccAllocate().setBid(bid).queryFirst();
					
					Thread t = new Thread(() -> {
						// 清空购物车
						tpBoutiqueCartService.clearCart(ShiroUtils.getUserId());
						
						// 自动流转一次
						try {
							tccAllocateService.flowPass(tccAllocate.getId(), ShiroUtils.getUserId());
						} catch (Exception e) {
							e.printStackTrace();
						}
					});
					t.start();
					
				}
			}
		}
		return r;
	}
	
	/**
	 * 新增
	 * @throws Exception 
	 */
	@PostMapping("/edit")
    @ResponseBody
	public R edit(HttpServletRequest request,
			String bid, Integer type, String subData) throws Exception{
		
		return tccAllocateService.edit(bid, subData, MenuId.TCC_Allocate);
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions(PERMISSIONS_EXPORT)
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccAllocateDetail cond, String conditions) throws Exception{
		
        cond = setSeachSql(cond);
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCC_Allocate)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
    	
        ExportExcelUtils<TpAmazonShopOrderDaily> util = new ExportExcelUtils<TpAmazonShopOrderDaily>(new TpAmazonShopOrderDaily());
        
        String toFilePath = util.exportExcel(listData, listField, "预约调拨单");
        UploadDto dto = commonApiServiceDetail.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }
	
	/**
	 * 流转通过
	 */
	@RequiresPermissions(PERMISSIONS_ADD)
	@PostMapping("/flowPass")
    @ResponseBody
	public R flowPass(HttpServletRequest request, Long id){
		try {
			return tccAllocateService.flowPass(id, ShiroUtils.getUserId());
		}  catch (IllegalArgumentException e) {
			e.printStackTrace();
			return R.error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转驳回
	 */
	@RequiresPermissions(PERMISSIONS_ADD)
	@PostMapping("/flowRefuse")
    @ResponseBody
	public R flowRefuse(HttpServletRequest request, Long id, String reason){
		try {
			return tccAllocateService.flowRefuse(id, reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}


	/**
	 * 流转驳回
	 */
	@RequiresPermissions(PERMISSIONS_ADD)
	@PostMapping("/flowInit")
	@ResponseBody
	public R flowInit(HttpServletRequest request, Long id, String reason){
		try {
			return tccAllocateService.flowInit(id, reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}




	/**
	 * 删除
	 * @throws Exception 
	 */
	@PostMapping("/delete")
    @ResponseBody
	public R delete(Long id){
		
		try {
			return tccAllocateService.deleteTrue(id);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("操作失败，请联系客服");
		}
	}
	
	/**
	 * 是否调拨过
	 * @throws Exception 
	 */
	@PostMapping("/hasAllocated")
    @ResponseBody
	public R hasAllocated(Long id){

		return tccAllocateService.hasAllocated(id);
	}
}
